package com.wande.dataplatform.filecollection.source.impl;

import cn.hutool.extra.ftp.Ftp;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.wande.common.core.exception.ServiceException;
import com.wande.dataplatform.filecollection.common.constant.FileCollectionConstants;
import com.wande.dataplatform.filecollection.source.IFileSource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * FTP文件来源实现
 *
 * @author wande
 */
@Slf4j
@Component
public class FtpFileSource implements IFileSource {

    @Override
    public String getSupportedSourceType() {
        return FileCollectionConstants.SourceType.FTP;
    }

    @Override
    public List<String> listFiles(String config) {
        JSONObject configJson = JSONUtil.parseObj(config);
        String host = configJson.getStr("host");
        int port = configJson.getInt("port", 21);
        String username = configJson.getStr("username");
        String password = configJson.getStr("password");
        String path = configJson.getStr("path", "/");
        String pattern = configJson.getStr("pattern", "*");

        List<String> files = new ArrayList<>();
        try (Ftp ftp = new Ftp(host, port, username, password)) {
            FTPClient ftpClient = ftp.getClient();
            FTPFile[] ftpFiles = ftpClient.listFiles(path);
            for (FTPFile ftpFile : ftpFiles) {
                if (ftpFile.isFile() && matchPattern(ftpFile.getName(), pattern)) {
                    files.add(path + "/" + ftpFile.getName());
                }
            }
            log.info("列出FTP文件, host={}, path={}, count={}", host, path, files.size());
        } catch (Exception e) {
            throw new ServiceException("列出FTP文件失败: " + e.getMessage());
        }
        return files;
    }

    @Override
    public InputStream getFileStream(String config, String filePath) {
        JSONObject configJson = JSONUtil.parseObj(config);
        String host = configJson.getStr("host");
        int port = configJson.getInt("port", 21);
        String username = configJson.getStr("username");
        String password = configJson.getStr("password");

        try (Ftp ftp = new Ftp(host, port, username, password)) {
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            // 从完整路径中提取文件名
            String fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
            String path = filePath.substring(0, filePath.lastIndexOf("/"));
            if (path.isEmpty()) {
                path = "/";
            }
            ftp.download(path, fileName, outputStream);
            return new ByteArrayInputStream(outputStream.toByteArray());
        } catch (Exception e) {
            throw new ServiceException("下载FTP文件失败: " + filePath);
        }
    }

    @Override
    public long getFileSize(String config, String filePath) {
        JSONObject configJson = JSONUtil.parseObj(config);
        String host = configJson.getStr("host");
        int port = configJson.getInt("port", 21);
        String username = configJson.getStr("username");
        String password = configJson.getStr("password");

        try (Ftp ftp = new Ftp(host, port, username, password)) {
            FTPClient ftpClient = ftp.getClient();
            FTPFile[] files = ftpClient.listFiles(filePath);
            if (files.length > 0) {
                return files[0].getSize();
            }
            throw new ServiceException("文件不存在: " + filePath);
        } catch (Exception e) {
            throw new ServiceException("获取FTP文件大小失败: " + filePath);
        }
    }

    @Override
    public boolean testConnection(String config) {
        try {
            JSONObject configJson = JSONUtil.parseObj(config);
            String host = configJson.getStr("host");
            int port = configJson.getInt("port", 21);
            String username = configJson.getStr("username");
            String password = configJson.getStr("password");

            try (Ftp ftp = new Ftp(host, port, username, password)) {
                return ftp.getClient().isConnected();
            }
        } catch (Exception e) {
            log.error("测试FTP连接失败", e);
            return false;
        }
    }

    private boolean matchPattern(String fileName, String pattern) {
        if ("*".equals(pattern)) {
            return true;
        }
        String regex = pattern.replace(".", "\\.").replace("*", ".*");
        return fileName.matches(regex);
    }
}
